package com.zky.factory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class SingletonFactory {
    // 保存单例对象
    private static final Map<Class<?>, Object> instances = new ConcurrentHashMap<>();

    // 根据 Class 获取单例
    @SuppressWarnings("unchecked")
    public static <T> T getInstance(Class<T> clazz) {
        return (T) instances.computeIfAbsent(clazz,(c)-> SingletonFactory.createInstance(clazz));
    }

    // 反射创建对象
    private static <T> T createInstance(Class<T> clazz) {
        try {
            return clazz.getDeclaredConstructor().newInstance();
        } catch (Exception e) {
            throw new RuntimeException("无法创建实例: " + clazz, e);
        }
    }
}
